import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from '@/router/routes'
import store from '@/store'

Vue.use(VueRouter)
// import Home from '../views/Home'
// import Search from '../views/Search'
// import Login from '../views/Login'
// import Register from '../views/Register'
const router = new VueRouter({
  mode: 'history',
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { x: 0, y: 0 }
    }
  },
})
let whiteList = [
  'home',
  'login',
  'register',
  'search',
  'detail',
  'addcartsuccess',
  'shopcart',
]
router.beforeEach((to, from, next) => {
  if (whiteList.includes(to.name) || store.state.user.user.token) {
    next()
  } else {
    next({
      name: 'login',
      query: { redirect: to.path },
    })
  }
})

const originPush = VueRouter.prototype.push
const originReplace = VueRouter.prototype.replace

VueRouter.prototype.push = function (location, okCallback, errCallback) {
  if (okCallback && errCallback) {
    return originPush.call(this, location, okCallback, errCallback)
  } else {
    originPush.call(this, location).catch(() => {})
  }
}

VueRouter.prototype.replace = function (location, okCallback, errCallback) {
  if (okCallback && errCallback) {
    return originReplace.call(this, location, okCallback, errCallback)
  } else {
    originReplace.call(this, location).catch(() => {})
  }
}

export default router
